// 初始化默认分类的云函数
'use strict';

const db = uniCloud.database()
const dbCmd = db.command

exports.main = async (event, context) => {
	// 默认分类数据
	const defaultCategories = [
		// 支出类别
		{ name: '餐饮', type: '支出', icon: 'icon-canyin' },
		{ name: '交通', type: '支出', icon: 'icon-jiaotong' },
		{ name: '购物', type: '支出', icon: 'icon-gouwu' },
		{ name: '娱乐', type: '支出', icon: 'icon-yule' },
		{ name: '医疗', type: '支出', icon: 'icon-yiliao' },
		{ name: '居住', type: '支出', icon: 'icon-juzhu' },
		{ name: '通讯', type: '支出', icon: 'icon-tongxun' },
		{ name: '学习', type: '支出', icon: 'icon-xuexi' },
		{ name: '其他支出', type: '支出', icon: 'icon-qita' },
		// 收入类别
		{ name: '工资', type: '收入', icon: 'icon-gongzi' },
		{ name: '奖金', type: '收入', icon: 'icon-jiangjin' },
		{ name: '理财', type: '收入', icon: 'icon-licai' },
		{ name: '兼职', type: '收入', icon: 'icon-jianzhi' },
		{ name: '其他收入', type: '收入', icon: 'icon-qita' }
	]
	
	try {
		// 检查是否已初始化
		const count = await db.collection('categories')
			.where({
				user_id: dbCmd.or([
					dbCmd.exists(false),
					null,
					''
				])
			})
			.count()
		
		if (count.total > 0) {
			return {
				code: 1,
				msg: '默认分类已存在，无需重复初始化'
			}
		}
		
		// 批量添加默认分类（不设置 user_id，作为公共分类）
		const addPromises = defaultCategories.map(item => {
			return db.collection('categories').add({
				...item,
				create_time: Date.now()
			})
		})
		
		await Promise.all(addPromises)
		
		return {
			code: 0,
			msg: '默认分类初始化成功',
			count: defaultCategories.length
		}
	} catch (error) {
		console.error('初始化失败:', error)
		return {
			code: -1,
			msg: '初始化失败: ' + error.message
		}
	}
}

